package com.yifeng.service.impl;

import com.yifeng.dao.RoleMapper;
import com.yifeng.po.Role;
import com.yifeng.po.RolePermission;
import com.yifeng.service.IRoleService;
import com.yifeng.util.BlogResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

	@Autowired
	private RoleMapper roleMapper;
	@Override
	public void delete(Serializable id) {
		
		//先删中间表
		roleMapper.removeRolePermission(id);
		//再删自己
		roleMapper.remove(id);
	}
	@Override
	public void add(Role t) {
		
		//先添加角色，添加完要返回Id
		roleMapper.save(t);
		//t_role_permisson 一条记录所需两个属性，可以把这两个属性封装成一个对象，保存时从这个对象中获取就ok
		List<RolePermission> rolePermissions = t.getRolePermissions();
		//查询对应关系：方案1：遍历出来一个一个插入，方案2：批量插入(采纳)
		roleMapper.saveRolePermissions(rolePermissions);
	}
	@Override
	public void update(Role t) {
		
		//修改自身信息
		roleMapper.update(t);
		//修改中间表信息-先删除后添加
		roleMapper.removeRolePermission(t.getId());
		roleMapper.saveRolePermissions(t.getRolePermissions());
	}


	public BlogResult getCount() {
		Integer count = roleMapper.getCount();
		return new BlogResult(200,"OK",count);
	}

	public Integer updateRole(String roleId,String[] pers) {

		Integer delResult = roleMapper.removeRolePermission(Long.valueOf(roleId));
		List<RolePermission> list = new ArrayList<RolePermission>();
		for(int i = 0;i<pers.length;i++){
			RolePermission rp = new RolePermission();
			rp.setRoleId(Long.valueOf(roleId));
			rp.setPermissionId(Long.valueOf(pers[i]));
			list.add(rp);
		}
		Integer addResult = roleMapper.saveRolePermissions(list);
		if(delResult>0 && addResult>0){
			return 1;
		}
		return -1;
	}
}